package com.fasteat.mall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasteat.common.entity.Result;
import com.fasteat.mall.entity.Logistics;
import com.fasteat.mall.entity.Orderform;
import com.fasteat.mall.entity.OrderformAftersales;
import com.fasteat.mall.entity.dto.AfterSalesProcessDto;
import com.fasteat.mall.entity.dto.Message;
import com.fasteat.mall.entity.vo.OrderformAfterSalesProductVo;
import com.fasteat.mall.entity.vo.OrderformProductVo;
import com.fasteat.mall.service.LogisticsService;
import com.fasteat.mall.service.OrderformAftersalesService;
import com.fasteat.mall.service.OrderformService;
import com.fasteat.mall.service.client.NotifyClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hy
 * @since 2021-02-20
 */
@RestController
@CrossOrigin
@Api(description = "订单售后接口")
@RequestMapping("/mall/orderformAftersales")
public class OrderformAftersalesController {
    @Autowired
    private OrderformAftersalesService aftersalesService;

    @Autowired
    private OrderformService orderformService;

    @Autowired
    private NotifyClient notifyClient;

    /**
     * 分页查看订单
     *
     * @return
     */
    @GetMapping("/vo//{start}/{end}/{userId}")
    @ApiOperation("按用户分页查看订单")
    public Result selectByStatus(@PathVariable(name = "start") @ApiParam(required = true, value = "尺寸") int start,
                                 @PathVariable(name = "end") @ApiParam(required = true, value = "当前页码") int end,
                                 @PathVariable(name = "userId") @ApiParam(required = true, value = "当前页码") String userId) {
        if(userId.equals(null)) {
            return Result.error("请输入用户id");
        }
        List<OrderformAfterSalesProductVo> orderformAfterSalesProductVos = aftersalesService.pageVoIAmAngry(start, end, userId);
        return Result.success().data(orderformAfterSalesProductVos);
    }

    /**
     * 通过售后订单ID获取订单信息
     *
     * @param orderformAftersalesId
     * @return
     */
    @GetMapping("findById/{orderformAftersalesId}")
    @ApiOperation("通过售后ID获取售后信息")
    public Result findById(@PathVariable(name = "orderformAftersalesId", required = true)
                           @ApiParam(value = "订单ID", required = true)
                                   String orderformAftersalesId) {
        if (StringUtils.isEmpty(orderformAftersalesId)) {
            return Result.error("查询失败");
        }
        // 从数据库中查询商品的信息
        OrderformAftersales orderform = aftersalesService.getById(orderformAftersalesId);
        return Result.success("查询成功").data(orderform);
    }

    /**
     * 新增物流
     * @param orderformAftersales
     * @return
     */
    @ApiOperation(value = "添加售后订单")
    @PostMapping
    public Result save(@RequestBody OrderformAftersales orderformAftersales) {
        if(StringUtils.isEmpty(orderformAftersales.getOrderformId()) || StringUtils.isEmpty(orderformAftersales.getUserId())) {
            return Result.error("订单Id或用户Id为空");
        }
        if(!orderformAftersales.getAftersalesStatus().equals(1)) {
            return Result.error("申请售后状态只能为1");
        }
        //保护处理信息不被恶意修改
        orderformAftersales.setProcessReason(null);
        orderformAftersales.setProcessResult(null);
        boolean result = aftersalesService.save(orderformAftersales);
        return result ?
                Result.success("添加成功")
                :
                Result.error("添加失败");
    }

    /**
     * 根据售后id删除售后订单
     * @param orderformAftersalesId
     * @return
     */
    @DeleteMapping(value = "/delete/{orderformAftersalesId}")
    @ApiOperation(value = "根据售后id删除售后订单")
    public Result deleteById(@PathVariable(name = "orderformAftersalesId", required = true)
                             @ApiParam(value = "orderformAftersalesId", required = true)
                                     String orderformAftersalesId) {
        if (orderformAftersalesId == null) {
            return Result.error("删除失败");
        }
        boolean result = aftersalesService.removeById(orderformAftersalesId);
        return result ?
                Result.success("删除成功")
                :
                Result.error("删除失败");
    }

    /**
     * 修改售后信息
     * @param orderformAftersales
     * @return
     */
    @ApiOperation(value = "根据售后id修改售后信息")
    @PutMapping
    public Result updateProduct(@RequestBody
                                @ApiParam(value = "售后Logistics对象", required = true)
                                        OrderformAftersales orderformAftersales) {
        if (StringUtils.isEmpty(orderformAftersales.getId())) {
            return Result.error("修改失败");
        }
        //保护处理信息不被恶意修改
        OrderformAftersales orderformAftersalesOrigin = aftersalesService.getById(orderformAftersales.getId());
        orderformAftersales.setProcessReason(orderformAftersalesOrigin.getProcessReason() == null ? null : orderformAftersalesOrigin.getProcessReason());
        orderformAftersales.setProcessResult(orderformAftersalesOrigin.getProcessResult() == null ? null : orderformAftersalesOrigin.getProcessResult());
        boolean result = aftersalesService.updateById(orderformAftersales);
        return result
                ?
                Result.success("修改成功")
                :
                Result.error("修改失败");
    }

    /**
     * 申请售后
     * @param orderformAftersales
     * @return
     */
    @ApiOperation(value = "申请售后")
    @PutMapping("/applyForAfterSales")
    public Result applyForAfterSales(@RequestBody
                                @ApiParam(value = "售后Logistics对象", required = true)
                                        OrderformAftersales orderformAftersales) {
        if (StringUtils.isEmpty(orderformAftersales.getReason()) || StringUtils.isEmpty(orderformAftersales.getImg())) {
            return Result.error("修改失败,部分字段为空");
        }
        orderformAftersales.setProcessReason(null);
        orderformAftersales.setProcessResult(null);
        orderformAftersales.setAftersalesStatus(1);
        //保护处理信息不被恶意修改
        boolean result = aftersalesService.save(orderformAftersales);
        return result
                ?
                Result.success("申请成功")
                :
                Result.error("申请失败");
    }

    /**
     * 分页查看用户售后订单
     *
     * @return
     */
    @GetMapping("/{size}/{current}/{userId}")
    @ApiOperation("分页查看用户售后订单")
    public Result queryASPages(@PathVariable(name = "size") @ApiParam(required = true, value = "尺寸") int size,
                                @PathVariable(name = "current") @ApiParam(required = true, value = "当前页码") int current,
                               @PathVariable(name = "userId") @ApiParam(required = true, value = "用户id") String userId) {
        size = size <= 0 ? 5 : size;
        current = current <= 0 ? 1 : current;
        Page<OrderformAftersales> page = new Page(current, size);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", userId);
        wrapper.orderByDesc("gmt_create");
        aftersalesService.page(page, wrapper);
        return Result.success().data(page);
    }

    /**
     * 分页查看售后订单
     *
     * @return
     */
    @GetMapping("/{size}/{current}")
    @ApiOperation("分页查看售后订单")
    public Result acceptProduct(@PathVariable(name = "size") @ApiParam(required = true, value = "尺寸") int size,
                                @PathVariable(name = "current") @ApiParam(required = true, value = "当前页码") int current) {
        size = size <= 0 ? 5 : size;
        current = current <= 0 ? 1 : current;
        Page<OrderformAftersales> page = new Page(current, size);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.orderByDesc("gmt_create");
        aftersalesService.page(page, wrapper);
        return Result.success().data(page);
    }

    /**
     * 同意申请
     * @param afterSalesProcessDto
     * @return
     */
    @ApiOperation(value = "同意申请")
    @Transactional
    @PutMapping("/acceptRefund")
    public Result acceptRefund(@RequestBody @ApiParam(value = "AfterSalesProcessDto对象", required = true)
                                       AfterSalesProcessDto afterSalesProcessDto) {
        if (StringUtils.isEmpty(afterSalesProcessDto.getOrderFormId())
                || StringUtils.isEmpty(afterSalesProcessDto.getUserId())
                || StringUtils.isEmpty(afterSalesProcessDto.getOrderformAfterSalesId())) {
            return Result.error("修改失败,请输入必要字段");
        }
        OrderformAftersales orderformAftersales = aftersalesService.getById(afterSalesProcessDto.getOrderformAfterSalesId());
        Orderform orderform = orderformService.getById(orderformAftersales.getOrderformId());
        Message message = new Message();
        //填充售后订单
        orderformAftersales.setAftersalesStatus(2);
        orderformAftersales.setProcessResult(afterSalesProcessDto.getProcessResult());
        orderformAftersales.setProcessReason(afterSalesProcessDto.getProcessRason());
        //填充订单售后状态
        orderform.setAftersalesStatus(2);
        //填充message
        message.setReceiverId(afterSalesProcessDto.getUserId());
        message.setPayload("您的售后处理已完成,请及时查看");
        message.setDescription("您的售后处理已完成,请及时查看");
        message.setTitle("您的售后处理已完成");
        boolean ret = orderformService.updateById(orderform);
        boolean result = aftersalesService.updateById(orderformAftersales);
        notifyClient.sendVerify(message);
        return result && ret
                ?
                Result.success("修改成功")
                :
                Result.error("修改失败");
    }

    /**
     * 拒绝申请
     * @param afterSalesProcessDto
     * @return
     */
    @ApiOperation(value = "拒绝申请")
    @Transactional
    @PutMapping("/refuseRefund")
    public Result refuseRefund(@RequestBody @ApiParam(value = "AfterSalesProcessDto对象", required = true)
                                       AfterSalesProcessDto afterSalesProcessDto) {
        if (StringUtils.isEmpty(afterSalesProcessDto.getOrderFormId())
                || StringUtils.isEmpty(afterSalesProcessDto.getUserId())
                || StringUtils.isEmpty(afterSalesProcessDto.getOrderformAfterSalesId())) {
            return Result.error("修改失败,请输入必要字段");
        }
        OrderformAftersales orderformAftersales = aftersalesService.getById(afterSalesProcessDto.getOrderformAfterSalesId());
        Orderform orderform = orderformService.getById(orderformAftersales.getOrderformId());
        Message message = new Message();
        //填充售后订单
        orderformAftersales.setAftersalesStatus(4);
        orderformAftersales.setProcessResult(afterSalesProcessDto.getProcessResult());
        orderformAftersales.setProcessReason(afterSalesProcessDto.getProcessRason());
        //填充订单售后状态
        orderform.setAftersalesStatus(4);
        //填充message
        message.setReceiverId(afterSalesProcessDto.getUserId());
        message.setPayload("您的售后处理已完成,请及时查看");
        message.setDescription("您的售后处理已完成,请及时查看");
        message.setTitle("您的售后处理已完成");
        boolean ret = orderformService.updateById(orderform);
        boolean result = aftersalesService.updateById(orderformAftersales);
        notifyClient.sendVerify(message);
        return result && ret
                ?
                Result.success("修改成功")
                :
                Result.error("修改失败");
    }

    /**
     * 完成退款
     * @param afterSalesProcessDto
     * @return
     */
    @ApiOperation(value = "完成退款")
    @Transactional
    @PutMapping("/finishRefund")
    public Result finishRefund(@RequestBody @ApiParam(value = "AfterSalesProcessDto对象", required = true)
                                       AfterSalesProcessDto afterSalesProcessDto) {
        if (StringUtils.isEmpty(afterSalesProcessDto.getOrderFormId())
                || StringUtils.isEmpty(afterSalesProcessDto.getUserId())
                || StringUtils.isEmpty(afterSalesProcessDto.getOrderformAfterSalesId())) {
            return Result.error("修改失败,请输入必要字段");
        }
        OrderformAftersales orderformAftersales = aftersalesService.getById(afterSalesProcessDto.getOrderformAfterSalesId());
        Orderform orderform = orderformService.getById(orderformAftersales.getOrderformId());
        Message message = new Message();
        //填充售后订单
        orderformAftersales.setAftersalesStatus(3);
        //填充订单售后状态
        orderform.setAftersalesStatus(3);
        //填充message
        message.setReceiverId(afterSalesProcessDto.getUserId());
        message.setPayload("您的退款已完成,请及时查看");
        message.setDescription("您的退款已完成,请及时查看");
        message.setTitle("您的退款已完成");
        boolean ret = orderformService.updateById(orderform);
        boolean result = aftersalesService.updateById(orderformAftersales);
        notifyClient.sendVerify(message);
        return result && ret
                ?
                Result.success("修改成功")
                :
                Result.error("修改失败");
    }
}

